import SocketInstance from "@/im-server/socket-instance";
import { ServeGetUserSetting } from "@/api/user";
import store from "@/store";
import { ServeGetTalkList } from "@/api/chat";
import { formatTalkItem } from "@/utils/talk";
export default {
  
  created() {
    // 判断用户是否登录
    
  },
  methods: {
    // 页面初始化设置
    initialize() {
      SocketInstance.connect();
    },

    // 加载用户相关设置信息，更新本地缓存
    loadUserSetting(update) {
      ServeGetUserSetting().then(async ({ code, result }) => {
        // 如果result有值说明用户创建成功
        if (result) {
    
          store.commit("UPDATE_USER_INFO", {
            id: result.id,
            face: result.face,
            name: result.name,
          });
          /**
           * 如果update有值说明当前用户是商家
           * 用户像商家进行聊天，商家进行刷新好友列表
           */
     
          if(update){
           await this.loadChatListInJs()
          }

          // 判断如果是有id说明是 用户像商家进行聊天。
          if (this.$route.query.id) {
            await this.createTalk(this.$route.query.id);
          } else {
            await this.loadChatList();
          }
        } else if (code === 200 && !result) {
          setTimeout(() => {
            this.loadUserSetting();
          }, 2000);
        }
      });
    },


     // 获取用户对话列表
     loadChatListInJs() {
    
      ServeGetTalkList()
        .then(({ code, result }) => {
          if (code !== 200) return false;

          store.commit("SET_UNREAD_NUM", 0);
          store.commit("SET_TALK_ITEMS", {
            items: result.map((item) => formatTalkItem(item)),
          });
          let index_name = sessionStorage.getItem("send_message_index_name");
          if (index_name) {
            sessionStorage.removeItem("send_message_index_name");
          }
        })
        .finally(() => {
         
        });
    },

    reload() {
      this.$root.$children[0].refreshView();
    },
  },
};
